#include <iostream>
#include "event.h"
#include "accept.h"
#include "global.h"
#include "errno.h"


using namespace std;

struct event_base* main_base;  
Accept *acc ;



int buildConnect(int port){

	int netfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if( netfd < 0 ){
		return -2;
	}

	struct sockaddr_in server_addr;
	bzero(&server_addr,sizeof(struct sockaddr_in));  
    server_addr.sin_family=AF_INET;  
    server_addr.sin_addr.s_addr=htonl(INADDR_ANY);  
    server_addr.sin_port = htons(port);  

	if(bind(netfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))==-1)  
    {  
        printf("error:%d!\n", errno);  
        return -3;  
    }

	::listen(netfd, 1024);

	int flags = ::fcntl(netfd, F_GETFL);  
    flags |= O_NONBLOCK;  
    fcntl(netfd, F_SETFL, flags);  

    event_set(&acc->netEvent, netfd, EV_READ | EV_PERSIST , dataInput, (void *)acc);  
	event_add(&acc->netEvent, NULL); 
	
	return netfd;

}



int main(){

	
	main_base = event_init();  
	if( main_base == NULL  ){
		return -1;
	}
	acc = new Accept();
	acc->setEventBase(main_base);
	int netfd = buildConnect(8081);
	if( netfd < 0 ){
		return -2;
	}
	acc->setFd(netfd);
	event_base_loop(main_base, 0);

	cout<<"hello"<<endl;
	return 0;

}
